package main

import (
	"flag"
	"fmt"
	"os/exec"
	"ssh/plugin"
	"strings"
	"sync"
)

var (
	wg sync.WaitGroup
	PWD string
)


func command(CMD string) string {
	cmd := exec.Command("bash","-c",CMD)
	b,err := cmd.Output()

	if err != nil {
		fmt.Println(err)
	}
	return string(b)
}


func ThreadCmd(PWD string){
	USERMAP,cmds := plugin.GetUserMap(PWD)
	for _,v := range USERMAP{
		wg.Add(1)
		go func (v plugin.UserInfo) {
			cmds := strings.Join(cmds,"\n")
			plugin.SshClient(v.IpPort,v.User,v.Passwd,cmds,&wg)
			//fmt.Println(v.IpPort,v.User,v.Passwd,cmds)
		}(v)
	}
	wg.Wait()
}

func Subproess(PWD string)  {
	USERMAP,cmds := plugin.GetUserMap(PWD)
	for _,v := range USERMAP{
		for _,cmd := range cmds{
			plugin.Sshclient(v.IpPort,v.User,v.Passwd,cmd)
			//fmt.Println(v.IpPort,v.User,v.Passwd,cmd)
		}
	}
}

func master()  {
	PWD = strings.TrimSpace(command("pwd")) + "/" + "host.conf"
	//PWD = "D:\\GOWORK\\src\\vscode\\08\\host.conf"
	var cmd string

	flag.StringVar(&cmd, "c", "", "执行单条命令") //cmd
	flag.Parse()

	if len(cmd) != 0{
		USERMAP,_ := plugin.GetUserMap(PWD)
		for _,v := range USERMAP{
				plugin.Sshclient(v.IpPort,v.User,v.Passwd,cmd)
		}
	}else {
		fmt.Println("当命令过多时推荐使用并发模式。")
		var selec string
		fmt.Print("请选择是否以并发模式执行(y/n):")
		_ ,err := fmt.Scanln(&selec)
		if err != nil {
			fmt.Println("请规范输入！")
		}
		if selec == "y" || selec == "Y"{
			ThreadCmd(PWD)
		}else if selec == "n" || selec == "N"{
			Subproess(PWD)
		}else {
			fmt.Println("请规范输入！")
		}
	}

}

func main() {

	master()

}